<template>
  <div className="login" style="height: 100%" @click="toHome"></div>
</template>
<script>
import { WX_AUTH_URL } from '../../app.config'
import { wxLogin, testLogin } from '../../api/user'
import { getPid, getLastPath } from '../../cookie'
import { mapActions } from 'vuex'

const pid = getPid()
export default {
  created () {
    // 开发模式
    if (process.env.NODE_ENV === 'development') {
      this.dev()
    } else {
      // 微信code
      this.code = this.$route.query.code
      if (!this.code) { // 不存在去请求
        window.location.href = WX_AUTH_URL
      } else {
        wxLogin(this.code, pid, true).then(res => {
          this.afterLogin(res)
        })
      }
    }
  },
  methods: {
    ...mapActions([
      'setUser'
    ]),
    toHome () {
      this.$router.replace('/')
    },
    afterLogin (res) {
      // 存在
      const user = res.data
      if (user.id) {
        const token = res.extra.token
        // 存储token 更新用户  进入首页
        if (token) {
          user.token = token
          this.setUser(user)
          const lastPath = getLastPath()
          // this.$router.replace('/')
          if (lastPath.length < 36 && lastPath && lastPath.length > 6 && lastPath.indexOf('login') < 0 && lastPath.indexOf('register') < 0) {
            this.$router.replace(lastPath)
            // this.$router.replace('/')
          } else {
            this.$router.replace('/')
          }
        } else {
          this.$router.push('/ban')
        }
      } else {
        // 直接去注册
        this.$router.push({
          path: '/register',
          query: {
            avatar: user.avatar,
            name: user.name,
            openId: user.openId,
            unionId: user.unionId,
            pid: pid
          }
        })
      }
    },
    dev () {
      // 115药店  53终端  28主管 10经理 12总管 36高于 27王凯 91总经理 101王总 43普杰明
      testLogin(43, pid).then(res => {
        this.afterLogin(res)
      })
    }
  }
}
</script>

<style scoped lang="stylus">

</style>
